package com.example.chatplatform.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.example.chatplatform.config.OSSConfig;
import com.example.chatplatform.service.FileOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class FileOssServiceImpl implements FileOssService {
    @Autowired
    private OSSConfig ossConfig;

    /**
     * 阿里云OSS文件上传
     *
     * @param file
     */
    @Override
    public String uploadToOss(MultipartFile file) {

        //获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint().replaceAll("^https?://", "");
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();

        //生成随机文件名
        String fileName = generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在OSS上bucket下的文件名
        String uploadFileName = "kongfeilong/" + fileName + extension;

        try {
            PutObjectResult result = ossClient.putObject(bucketName, uploadFileName, file.getInputStream());
            //拼装返回路径
            if (result != null) {
                return "https://"+bucketName+"."+endPoint+"/"+uploadFileName;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //OSS关闭服务
            ossClient.shutdown();
        }
        return null;
    }

    /**
     * 阿里云OSS删除文件
     *
     * @param fileUrl 要删除的文件的完整URL
     * @return 删除是否成功
     */
    @Override
    public Boolean deleteFileFromOss(String fileUrl) {
        // 获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint().replaceAll("^https?://", "");
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        // 创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        try {
            // 从文件URL获取文件的key
            String fileKey = getFileKeyFromUrl(fileUrl, bucketName, endPoint);
            if (fileKey != null) {
                // 删除文件
                ossClient.deleteObject(bucketName, fileKey);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // OSS关闭服务
            ossClient.shutdown();
        }
        return false;
    }

    /**
     * 从文件URL获取文件的key
     *
     * @param fileUrl  文件的完整URL
     * @param bucketName 桶名称
     * @param endPoint   终端节点
     * @return 文件的key
     */
    private String getFileKeyFromUrl(String fileUrl, String bucketName, String endPoint) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return null;
        }
        // 去掉URL前缀
        String urlWithoutPrefix = fileUrl.replace("https://" + bucketName + "." + endPoint + "/", "");
        return urlWithoutPrefix;
    }

    /**
     * 获取随机字符串
     * @return
     */
    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }
    /**
     * 阿里云OSS批量删除文件
     *
     * @param fileUrls 要删除的文件的完整URL列表
     * @return 删除是否成功，只要有一个文件失败就返回false
     */
    @Override
    public Boolean deleteListFilesFromOss(List<String> fileUrls) {
        if (fileUrls == null || fileUrls.isEmpty()) {
            return false;
        }

        // 获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint().replaceAll("^https?://", "");
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        // 创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        boolean success = true;

        try {
            for (String fileUrl : fileUrls) {
                if (fileUrl == null || fileUrl.isEmpty()) {
                    success = false;
                    continue;
                }

                // 从文件URL获取文件的key
                String fileKey = getFileKeyFromUrl(fileUrl, bucketName, endPoint);
                if (fileKey != null) {
                    // 删除文件
                    ossClient.deleteObject(bucketName, fileKey);
                } else {
                    success = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            // OSS关闭服务
            ossClient.shutdown();
        }

        return success;
    }
}